package com.forum.controller;

import com.forum.dto.UserDTO;
import com.forum.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务Feign接口控制器
 */
@RestController
@RequiredArgsConstructor
public class UserFeignController {
    
    private final UserService userService;
    
    /**
     * 根据用户ID获取用户名
     *
     * @param userId 用户ID
     * @return 用户名
     */
    @GetMapping("/name/{userId}")
    public String getUsernameById(@PathVariable Long userId) {
        try {
            UserDTO user = userService.getUserById(userId);
            return user != null ? user.getUsername() : "用户_" + userId;
        } catch (Exception e) {
            // 降级处理
            return "用户_" + userId;
        }
    }
    
    /**
     * 检查用户是否存在
     *
     * @param userId 用户ID
     * @return 是否存在
     */
    @GetMapping("/exists/{userId}")
    public Boolean checkUserExists(@PathVariable Long userId) {
        try {
            return userService.getUserById(userId) != null;
        } catch (Exception e) {
            // 降级处理
            return true;
        }
    }
    
    /**
     * 获取用户基本信息
     *
     * @param userId 用户ID
     * @return 用户基本信息（包含用户名、头像等）
     */
    @GetMapping("/api/users/basic-info/{userId}")
    public Map<String, Object> getUserBasicInfo(@PathVariable Long userId) {
        Map<String, Object> userInfo = new HashMap<>();
        try {
            UserDTO user = userService.getUserById(userId);
            if (user != null) {
                userInfo.put("id", user.getId());
                userInfo.put("username", user.getUsername());
                userInfo.put("picture", user.getPicture());
                userInfo.put("gender", user.getGender());
                userInfo.put("email", user.getEmail());
            } else {
                // 用户不存在时的默认值
                userInfo.put("id", userId);
                userInfo.put("username", "用户_" + userId);
                userInfo.put("picture", "/default-avatar.png");
            }
        } catch (Exception e) {
            // 降级处理
            userInfo.put("id", userId);
            userInfo.put("username", "用户_" + userId);
            userInfo.put("picture", "/default-avatar.png");
        }
        return userInfo;
    }
} 